<template>
	<n-card class="wh-full" v-bind:loading="loading">
		<n-card title="表/对象" class="mb-4">
			<!-- 编辑表信息、匹配模版 -->
			<n-form ref="tableFormRef" label-placement="left" :label-width="80" :model="formData" :rules="tableRule">
				<n-space item-style="flex:1" class="w-full">
					<n-form-item label="表名" path="name">
						<n-input v-model:value="formData.name" placeholder="请输入" />
					</n-form-item>
					<n-form-item label="作者名" path="formData.author">
						<n-input v-model:value="formData.author" placeholder="请输入" />
					</n-form-item>
					<n-form-item label="包前缀" path="formData.prePackage">
						<n-input v-model:value="formData.prePackage" placeholder="请输入" />
					</n-form-item>
				</n-space>
				<n-space item-style="flex:1" class="w-full">
					<n-form-item label="模块名" path="formData.moduleName">
						<n-input v-model:value="formData.moduleName" placeholder="请输入" />
					</n-form-item>
					<n-form-item label="业务名" path="formData.className">
						<n-input v-model:value="formData.className" placeholder="请输入" />
					</n-form-item>
					<n-form-item label="数据库" path="formData.dbType">
						<n-input v-model:value="formData.dbType" disabled />
					</n-form-item>

				</n-space>
				<n-space class="w-full" :wrap-item="false">
					<n-form-item label="模版组" path="formData.groupId" style="flex:1">
						<n-select v-model:value="formData.groupId" :options="groupOptions" :on-update:value="refreashTemplateExtra"
							label-field="name" value-field="id" />
					</n-form-item>
					<n-form-item label="表注释" path="formData.comment" style="flex:2">
						<n-input v-model:value="formData.comment" placeholder="请输入" type="textarea" />
					</n-form-item>
				</n-space>

			</n-form>
			<n-space item-style="flex:1" class="w-full">
				<n-card title="模版所需扩展变量" size="small" header-style="font-size: 1rem;" v-if="curTemplateGroup">
					<n-space>
						<n-tooltip trigger="hover" v-for="value, key in curTemplateGroup.extra">
							<template #trigger>
								<n-tag class="cursor-pointer " type="info" @click="()=>handleCopy(key)"> {{ key }} : {{value }} </n-tag>
							</template>
							点击复制
						</n-tooltip>
					</n-space>
				</n-card>
				<n-card title="自定义表级别扩展变量" size="small" header-style="font-size: 1rem;">
					<extra-var :ref="ExtraRef" v-if="formData.id" v-model:extra="formData.extra"/>
				</n-card>
			</n-space>
		</n-card>
		<n-card title="列/字段">
			<!-- 编辑列信息 -->
			<n-data-table :columns="columnFromTable" :data="formData.columns"  :row-key="(it) => it.id" />
		</n-card>
		<n-space justify="center" class="mt-4">
			<n-button type="primary" @click="handleSubmitForm">确定</n-button>
			<n-button @click="hendleCloseModal">取消</n-button>
		</n-space>
	</n-card>
</template>

<script  setup lang='tsx' >
import { h, onMounted, ref, unref } from 'vue';
import { featchGenTable, featchAddGenTable, featchUpadteGenTable } from '@/service/api/genCode/index'
import { featchGroupOptions } from '@/service/api/templateManage/index'
import { GenTable, GenTableColumn } from '~/src/views/gen-code-code/index';
import { GenGroup } from '~/src/views/template-manage/group/index';
import { useRouter } from 'vue-router';
import { useRouterPush } from '@/composables';
import { useTabStore } from '@/store';
import { DataTableColumns, FormInst } from 'naive-ui';
import { BusinessStatus } from '~/src/enum';
import { handleCopy } from "@/utils/common/business";

import extraVar from "./extraVar.vue";

const loading = ref<boolean>(false)
const $route = useRouter()
const routerPush = useRouterPush()
const fullPath = $route.currentRoute.value.fullPath;
const tabStore = useTabStore()
const formData = ref<GenTable>({})
const curTemplateGroup = ref<GenGroup>({ items: [] })
const tableFormRef = ref<FormInst | null>(null)
// const inputKeyRef = (el:any)=>{
// 	if(el)inputKeyRefList.value.push(el)
// }
const tableRule = {
	name: { required: true, message: "请输入表名", trigger: 'input' },
}
const extraRefList = ref<any[]>([]);
const ExtraRef = (el:any)=>{
	if(el)extraRefList.value.push(el)
}
const columnFromTable: DataTableColumns<GenTableColumn> = [
	{
		type: 'expand', minWidth: "30",
		renderExpand: (rowData,rowIndex) => {
			return h(extraVar,{extra:rowData.extra,ref:ExtraRef,"onUpdate:extra":(extra)=>{formData.value.columns[rowIndex].extra = extra}})
		}
	},
	{
		title: "列名", key: "name", minWidth: "120",
		render(rowData, rowIndex) {
			return <>
				<n-input value={rowData.name} placeholder="列名" onUpdateValue={(v: string) => { rowData.name = v }} />
			</>
		},
	},
	{
		title: "列类型", key: "sourceType", minWidth: "120",
		render(rowData, rowIndex) {
			return <>
				<n-input value={rowData.sourceType} placeholder="列类型" onUpdateValue={(v: string) => { rowData.sourceType = v }} />
			</>
		},
	},
	{
		title: "字段名", key: "fieldName", minWidth: "120",
		render(rowData, rowIndex) {
			return <>
				<n-input value={rowData.fieldName} placeholder="字段名" onUpdateValue={(v: string) => { rowData.fieldName = v }} />
			</>
		},
	},
	{
		title: "字段类型", key: "javaType", minWidth: "120",
		render(rowData, rowIndex) {
			return <>
				<n-input value={rowData.javaType} placeholder="字段类型" onUpdateValue={(v: string) => { rowData.javaType = v }} />
			</>
		},
	},
	{
		title: "表单类型", key: "formType", minWidth: "120",
		render(rowData, rowIndex) {
			return <>
				<n-input value={rowData.formType} placeholder="表单类型" onUpdateValue={(v: string) => { rowData.formType = v }} />
			</>
		},
	},
	{
		title: "查询类型", key: "queryType", minWidth: "120",
		render(rowData, rowIndex) {
			return <>
				<n-input value={rowData.queryType} placeholder="查询类型" onUpdateValue={(v: string) => { rowData.queryType = v }} />
			</>
		},
	},
	{
		title: "主键", key: "isPk", minWidth: "50",
		render(rowData, rowIndex) {
			return <>
				<n-switch value={rowData.isPk} checkedValue={BusinessStatus.Yse} uncheckedValue={BusinessStatus.No} onUpdateValue={(v: BusinessStatus) => { rowData.isPk = v }} />
			</>
		},
	},
	{
		title: "必填", key: "isRequired", minWidth: "50",
		render(rowData, rowIndex) {
			return <>
				<n-switch value={rowData.isRequired} checkedValue={BusinessStatus.Yse} uncheckedValue={BusinessStatus.No} onUpdateValue={(v: BusinessStatus) => { rowData.isRequired = v }} />
			</>
		},
	},
	{
		title: "新增", key: "isInsert", minWidth: "50",
		render(rowData, rowIndex) {
			return <>
				<n-switch value={rowData.isInsert} checkedValue={BusinessStatus.Yse} uncheckedValue={BusinessStatus.No} onUpdateValue={(v: BusinessStatus) => { rowData.isInsert = v }} />
			</>
		},
	},
	{
		title: "修改", key: "isEdit", minWidth: "50",
		render(rowData, rowIndex) {
			return <>
				<n-switch value={rowData.isEdit} checkedValue={BusinessStatus.Yse} uncheckedValue={BusinessStatus.No} onUpdateValue={(v: BusinessStatus) => { rowData.isEdit = v }} />
			</>
		},
	},
	{
		title: "查询", key: "isQuery", minWidth: "50",
		render(rowData, rowIndex) {
			return <>
				<n-switch value={rowData.isQuery} checkedValue={BusinessStatus.Yse} uncheckedValue={BusinessStatus.No} onUpdateValue={(v: BusinessStatus) => { rowData.isQuery = v }} />
			</>
		},
	},
	{
		title: "列表", key: "isList", minWidth: "50",
		render(rowData, rowIndex) {
			return <>
				<n-switch value={rowData.isList} checkedValue={BusinessStatus.Yse} uncheckedValue={BusinessStatus.No} onUpdateValue={(v: BusinessStatus) => { rowData.isList = v }} />
			</>
		},
	},
	{
		title: "注释", key: "comment", minWidth: "80",
		render(rowData, rowIndex) {
			return <>
				<n-input value={rowData.comment} placeholder="注释" onUpdateValue={(v: string) => { rowData.comment = v }} />
			</>
		},
	},
]
const groupOptions = ref<GenTable>([])
async function initFormData(id: Common.IdType): GenTable {
	const { data,error } = await featchGenTable(id)
	if(error){
		hendleCloseModal()
		return false;
	}
	data.extra = data.extra ? data.extra : {}
	data?.columns?.forEach(it => {
		it.extra = it.extra ? it.extra : {}
	});
	formData.value = data!
	if (data!.groupId) refreashTemplateExtra(data!.groupId)
}
function handleFetchResult(res: Service.RequestResult<unknown>) {
	if (!res.error) {
		window.$message?.success("提交成功")
		hendleCloseModal()
	}
}
function vaildColumnsFrom(): boolean {
	const columns: GenTableColumn[] = formData.value.columns
	if (!(columns && columns.length > 0)) {
		window.$message?.error("列对象为空！请检查数据后重新提交")
		return false
	}
	for (let i = 0; i < columns.length; i++) {
		const column = columns[i]
		//@ts-ignore
		if (!(column.name && column.fieldName && column.sourceType && column.javaType && column.formType && column.queryType)) {
			console.error(column)
			window.$message?.error("列对象校验失败！请检查数据后重新提交")
			return false
		}
	}
	return true;
}
function handleSubmitForm() {
	tableFormRef.value?.validate(e => {
		if (!e && vaildColumnsFrom()) {
			// 刷新 extra
			extraRefList.value.forEach(it=>it.arr2Extra())
			//	const extra:Record<string,string> = extraValRef?.value.refreshExtra()
			const value = unref(formData.value)
			//value.extra = extra
			if (value.id) {
				featchUpadteGenTable(value).then(handleFetchResult)
			} else {
				featchAddGenTable(value).then(handleFetchResult)
			}
		}
	})
}
function hendleCloseModal() {
	routerPush.routerBack()
	tabStore.removeTab(fullPath)
}
async function initGroupOptions() {
	loading.value = true
	const { data } = await featchGroupOptions()
	groupOptions.value = data!;
	loading.value = false
}
function refreashTemplateExtra(val: Common.IdType) {
	formData.value.groupId = val;
	curTemplateGroup.value = { items: [] }
	for (const i in groupOptions.value) {
		const item = groupOptions.value[i]
		if (item.id == val) {
			curTemplateGroup.value = item
		}
	}

}


onMounted(async () => {
	const query = $route.currentRoute.value.query
	if (query && query.id) {
		initFormData(query.id as string)
	}
	initGroupOptions()

})

</script>

<style lang='scss' scoped></style>
